# -*- coding: utf-8 -*-
from flask import Blueprint, render_template, request, jsonify, current_app, url_for, redirect, g

from application import db
from common.libs.UserSerivice import UserService
from web.models.user import User

route_user = Blueprint('user_page', __name__)


@route_user.route("/login", methods=['GET', 'POST'])
def login():
    """get请求返回登录页面，post验证登录"""
    # 返回给客户端的数据，json格式
    resp = {"code": 200, "msg": "登录成功", "data": {}}
    if request.method == "GET":
        return render_template("user/login.html")
    elif request.method == "POST":
        # 以下处理POST请求
        # 1.获取用户名与密码
        req = request.values
        login_name = req["login_name"] if "login_name" in req else ""
        login_pwd = req["login_pwd"] if "login_pwd" in req else ""
        # 2.对用户名密码进行格式验证
        if (not login_name) or len(login_name) < 1:
            resp["code"] = -1
            resp["msg"] = "请输入正确的登录用户名"
            return jsonify(resp)
        if (not login_pwd) or len(login_pwd) < 1:
            resp["code"] = -1
            resp["msg"] = "请输入正确的密码"
            return jsonify(resp)
        # 3.通过数据库验证用户名密码的合法性
        user_info = User.query.filter_by(login_name=login_name).first()
        if not user_info:  # 数据库查不到
            resp["code"] = -1
            resp["msg"] = "用户名不存在"
            return jsonify(resp)
        # 验证密码
        salt = user_info.login_salt  # 用于给密码加密的盐值(加密的密钥)
        # 通过 密文= 密码明文(login_pwd)+加密的密钥(salt)+加密算法(genPwd)
        gen_pwd = UserService.genPwd(login_pwd, salt)  # 跟注册时相同的加密机制
        if user_info.login_pwd != gen_pwd:
            resp["code"] = -1
            resp["msg"] = "密码不正确"
            return jsonify(resp)
        # 用户名存在，密码正确，则把登录信息写入到resp的data中
        # 登录成功
        # resp = {"code": 200, "msg": "登录成功", "data": {}}
        resp['data']['username'] = login_name
        resp['data']['password'] = login_pwd

        # 把登录状态信息 通过 cookie实现 保持
        response = jsonify(resp)
        # response.set_cookie('username',login_name)
        # response.set_cookie('password',login_pwd)
        # 对cookie信息加密  cookie_str= 123423abcdaefb(32位16进制数)#1(uid)
        cookie_str = UserService.genAuthCode(user_info) + "#" + str(user_info.uid)
        response.set_cookie(current_app.config.get('AUTH_COOKIE_NAME'), cookie_str)
        return response
    else:
        # resp = {"code": 200, "msg": "登录成功", "data": {}}
        resp["code"] = -1
        resp["msg"] = "请求方式有误"
        return resp


@route_user.route("/edit", methods=['GET', 'POST'])
def edit():
    """编辑个人信息"""
    resp = {"code": 200, "msg": "操作成功", "data": {}}
    if request.method == "GET":
        return render_template("user/edit.html")
    elif request.method == "POST":
        # 1.取得姓名和邮箱
        req = request.values
        nickname = req["nickname"] if "nickname" in req else ""
        email = req["email"] if "email" in req else ""
        if (not nickname) or len(nickname) < 1:
            resp["code"] = -1
            resp["msg"] = "请输入符合规范的姓名"
            return jsonify(resp)
        if (not email) or len(email) < 1:
            resp["code"] = -1
            resp["msg"] = "请输入符合规范的邮箱"
            return jsonify(resp)
        # 更新数据库了
        # 修改当前登录人姓名和邮箱
        user_info = g.current_user
        user_info.nickname = nickname
        user_info.email = email
        # 提交到数据库
        db.session.add(user_info)
        db.session.commit()
        return jsonify(resp)
    else:
        #  resp = {"code": 200, "msg": "操作成功", "data": {}}
        resp["code"] = -1
        resp["msg"] = "请求方式有误"
        return jsonify(resp)


@route_user.route("/reset-pwd", methods=['GET', 'POST'])
def resetPwd():
    """修改个人密码"""
    resp = {"code": 200, "msg": "操作成功", "data": {}}
    if request.method == "GET":
        return render_template("user/reset_pwd.html")
    elif request.method == "POST":
        # 1.取得用户输入的新的密码
        req = request.values
        old_password = req["old_password"] if "old_password" in req else ""
        new_password = req["new_password"] if "new_password" in req else ""
        if (not old_password) or len(old_password) < 1:
            resp["code"] = -1
            resp["msg"] = "请输入正确的原密码"
            return jsonify(resp)
        if (not new_password) or len(new_password) < 6:
            resp["code"] = -1
            resp["msg"] = "请输入不少于6位的新密码"
            return jsonify(resp)
        if old_password == new_password:
            resp["code"] = -1
            resp["msg"] = "新旧密码一致"
            return jsonify(resp)
        # 校验旧密码
        user_info = g.current_user
        salt = user_info.login_salt
        # old_password=123456    gen_pwd:816440c40b7a9d55ff9eb7b20760862c
        gen_pwd = UserService.genPwd(old_password, salt)  # 跟注册时相同的加密机制
        if user_info.login_pwd != gen_pwd:
            resp["code"] = -1
            resp["msg"] = "原密码不对~"
            return jsonify(resp)
        # 设置新密码
        gen_pwd = UserService.genPwd(new_password, salt)
        user_info.login_pwd = gen_pwd
        db.session.add(user_info)
        db.session.commit()

        # 更新cookie
        response = jsonify(resp)
        cokie_str = UserService.genAuthCode(user_info) + "#" + str(user_info.uid)
        response.set_cookie(current_app.config.get("AUTH_COOKIE_NAME"), cokie_str, max_age=7 * 24 * 60 * 60)
        return response
    else:
        #  resp = {"code": 200, "msg": "操作成功", "data": {}}
        resp["code"] = -1
        resp["msg"] = "请求方式有误"
        return jsonify(resp)


# 登出操作
@route_user.route("/logout")
def logout():
    # 登出执行后，进入到登录页面
    response = redirect(url_for('user_page.login'))
    # 删除登录时设置的cookie
    response.delete_cookie(current_app.config.get('AUTH_COOKIE_NAME'))
    return response
